<template>
  <div class="index" style="user-select: none;">
    <!-- 标题 -->
    <module-title :title="moduleTitle"></module-title>

    <!-- 主体 start -->
    <el-card>
      <!-- 选项卡 -->
      <div class="option-card">
        <div
          :class="optionFlag ? 'card-item card-item-active' : 'card-item'"
          @click="optionFlag = true"
        >
          已有任务
        </div>
        <div
          :class="optionFlag ? 'card-item' : 'card-item card-item-active'"
          @click="addAutoMissionClick()"
        >
          新增任务
        </div>
      </div>

      <!-- 已有任务 start -->
      <div v-if="optionFlag">
        <div class="list">
          <div class="list-head">
            <span class="list-head-text list-left-column">任务名称</span>
            <span class="list-head-text list-middle-column">任务流程</span>
            <span class="list-head-text list-right-column">操作</span>
          </div>
          <div
            class="list-body"
            v-for="(item, index) in missionList"
            :key="item.id"
          >
            <span class="list-body-content list-left-column">{{
              item.taskName
            }}</span>
            <span class="list-body-content list-middle-column work-flow">
              <span v-for="(i, idx) in item.process" :key="idx">
                {{ i }}
              </span>
            </span>
            <span class="list-body-content list-right-column operation-button">
              <span class="modify-button" @click="modifyMissionBtnClick(index)"
                >修改</span
              >
              <span
                class="disabled-button"
                @click="delAutoMissionState(item)"
                >删除</span
              >
            </span>
          </div>
          <div class="noneList" v-if="missionList.length === 0">
            暂无数据
          </div>
        </div>
        <!-- 分页 -->
        <el-pagination
          style="margin: 50px 0 23px 0; text-align: center"
          :page-size="6"
          :pager-count="5"
          layout="total, prev, pager, next"
          :total="missionTotal"
          @prev-click="paginationPrevClick"
          @next-click="paginationNextClick"
          @current-change="paginationNextChange"
        ></el-pagination>
      </div>
      <!-- 已有任务 end -->

      <!-- 新增任务 start -->
      <div v-else>
        <div class="add-form">
          <el-scrollbar style="height: 100%">
            <el-form
              class="add-form-item"
              v-for="(item, index) in addForm"
              :key="index"
            >
              <div class="add-form-item-number">
                <i class="order-number">{{ index + 1 }}</i>
              </div>
              <el-form-item label="选择App：" class="add-form-item-app">
                <el-select
                  v-model="item.appName"
                  placeholder="请选择"
                  @change="chooseAppInAdd(index, $event)"
                >
                  <el-option
                    v-for="i in appAndMissionList"
                    :key="i.id"
                    :label="i.name"
                    :value="i.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="任务名称：" class="add-form-item-mission">
                <el-select
                  v-model="item.taskName"
                  placeholder="请选择"
                  no-data-text="请先选择App"
                  @visible-change="getMissionFromApp(item, $event)"
                  ref="missionSelector"
                >
                  <el-option
                    v-for="item in existMissionList"
                    :key="item.id"
                    :label="item.taskName"
                    :value="item.taskName"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <div
                class="add-form-item-delete"
                @click="delFormItem(index)"
                v-show="addForm.length > 2"
              >
                <i class="delete-button">-</i>
              </div>
            </el-form>
            <div
              class="add-one-button"
              @click="addFormItem()"
              v-show="addForm.length < 10"
            >
              <b
                style="font-size: 50px; font-weight: normal; vertical-align: middle"
                >+</b
              >
              添加连续任务
            </div>
          </el-scrollbar>
        </div>
        <!-- 提交按钮 -->
        <div class="add-form-button">
          <el-button class="submit-button" @click="dialogFormVisible = true"
            >提交任务</el-button
          >
        </div>
      </div>
      <!-- 新增任务 end -->
    </el-card>
    <!-- 主体 end -->

    <!-- 弹窗 -->
    <el-dialog title="请确认任务名称" :visible.sync="dialogFormVisible" width="500px">
      <el-form :model="form">
        <el-form-item label="任务名称" :label-width="formLabelWidth">
          <el-input v-model="form.taskName" autocomplete="off" style="width: 200px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAutoMission()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改任务流程 -->
    <el-dialog
      id="modDialog"
      title="修改任务"
      center
      width="35%"
      :visible.sync="modifyMissionDialog"
    >
      <el-scrollbar style="height: 380px">
        <div
          style="display: flex; font-size: 16px"
          v-for="(item, index) in modifyForm"
          :key="index"
        >
          <div style="width: 20%; text-align: center">
            <i class="order-number" style="margin-top: 6px;">
              {{ index + 1 }}
            </i>
          </div>

          <div style="width: 80%">
            <div style="margin-bottom: 18px">
              选择App：
              <el-select
                v-model="item.appName"
                placeholder="请选择"
                @change="chooseApp(index, $event)"
              >
                <el-option
                  v-for="i in appAndMissionList"
                  :key="i.id"
                  :label="i.name"
                  :value="i.name"
                >
                </el-option>
              </el-select>
            </div>

            <div style="margin-bottom: 30px">
              任务名称：
              <el-select
                v-model="item.taskName"
                placeholder="请选择"
                no-data-text="请先选择App"
                @visible-change="getMissionFromApp(item, $event)"
              >
                <el-option
                  v-for="i in existMissionList"
                  :key="i.id"
                  :label="i.taskName"
                  :value="i.taskName"
                >
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
      </el-scrollbar>
      <div class="modify-dialog-button">
        <el-button class="cancel-button" @click="cancelButtonClick()"
          >取消</el-button
        >
        <el-button class="confirm-button" @click="modifyButtonClick()"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createSign } from "@/utils/sign.js";
import API from "@/network/api/smsApi.js";

import ModuleTitle from "@/components/content/ModuleTitle.vue";
export default {
  name: "index",
  data() {
    return {
      moduleTitle: "连续任务",
      missionTotal: 0, // 已有任务总数
      optionFlag: true,
      dialogFormVisible: false,
      modifyMissionDialog: false, // 是否展示修改弹窗
      missionList: [], // 已有任务列表
      appAndMissionList: [], // 已有App列表
      // 选中App下的独立任务
      existMissionList: [],
      // 已有任务查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 6
      },
      // 新增参数
      addForm: [
        {
          appName: "",
          taskName: ""
        },
        {
          appName: "",
          taskName: ""
        }
      ],
      form: {
        taskName: ''
      },
      formLabelWidth: '120px',
      // 修改参数
      modifyForm: [],
      modifyIndex: 0, // 当前修改的任务index
      modifyAppId: 0, // 当前修改的任务所属appId
      // 公共参数
      publicForm: {
        timestamp: ""
      },
      delForm: {
        deleted: true,
        id: '',
        timestamp: ''
      },
      delSign: {
        sign: ''
      }
    };
  },
  created() {
    this.getAutoMission();
    this.getAppAndMissionList();
  },
  computed: {
    // 新增连续任务的appId
    addAppId() {
      let addAppName = this.addForm[0].appName;
      let id = 0;
      for (let i = 0; i < this.appAndMissionList.length; i++) {
        if (this.appAndMissionList[i].name === addAppName) {
          id = this.appAndMissionList[i].id;
        }
      }
      return id;
    }
  },
  methods: {
    /**
     * 页面逻辑
     */
    delAutoMissionState(item) {
      this.delForm.id = item.id
      this.delForm.timestamp = +new Date();
      console.log(this.delForm, 'this.delForm')
      this.delSign.sign = createSign(
        JSON.stringify({
          ...this.delForm,
        })
      );
      API.delContinuousTask( {
        ...this.delForm,
        ...this.delSign
      }).then(res => {
        console.log(res)
        if (res.data.data === '删除成功') {
          this.$message.success('删除成功')
          location.reload()
        }
      })
    },
    // 新增任务
    addAutoMissionClick() {
      this.optionFlag = false;
      this.addForm = [
        {
          appName: "",
          taskName: ""
        },
        {
          appName: "",
          taskName: ""
        }
      ];
    },

    // 任务修改
    modifyMissionBtnClick(index) {
      this.modifyMissionDialog = true;
      this.modifyIndex = index;
      this.existMissionList = [];
      this.getOneAutoMission();
    },

    // 取消
    cancelButtonClick() {
      this.modifyMissionDialog = false;
    },

    // 添加一行任务项
    addFormItem() {
      let newItem = {
        appName: "",
        taskName: ""
      };
      this.addForm.push(newItem);
      console.log(this.addForm);
    },

    // 任务名称选择器操作
    getMissionFromApp(item, flag) {
      if (flag) {
        for (let i = 0; i < this.appAndMissionList.length; i++) {
          if (this.appAndMissionList[i].name === item.appName) {
            this.getMissionList(this.appAndMissionList[i].id);
            break;
          }
        }
      } else {
        this.existMissionList = [];
      }
    },

    // 删除指定行任务项
    delFormItem(index) {
      this.addForm.splice(index, 1);
    },

    chooseAppInAdd(index, item) {
      this.addForm[index].taskName = "";
    },

    // 选择app，展示app下的任务
    chooseApp(index, item) {
      this.modifyForm[index].taskName = "";
      for (let i = 0; i < this.appAndMissionList.length; i++) {
        if (this.appAndMissionList[i].name === item) {
          this.modifyAppId = this.appAndMissionList[i].id;
        }
      }
    },

    // 分页
    paginationPrevClick(page) {
      this.queryForm.pageNum = page;
      this.getAutoMission();
    },
    paginationNextClick(page) {
      this.queryForm.pageNum = page;
      this.getAutoMission();
    },
    paginationNextChange(page) {
      this.queryForm.pageNum = page;
      this.getAutoMission();
    },

    /**
     * 网络请求
     */

    // 查询已有连续任务列表
    async getAutoMission() {
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      const organForm = {
        organId: JSON.parse(localStorage.getItem('updateUserInfo')).organId
      }
      this.publicForm.sign = createSign(
        JSON.stringify({
          ...this.publicForm,
          ...this.queryForm,
          ...organForm
        })
      );
      await API.getAutoMission({
        ...this.publicForm,
        ...this.queryForm,
        ...organForm
      }).then(res => {
        if (res.data.code === 0) {
          this.missionTotal = res.data.data.total;
          this.missionList = res.data.data.records;
          for (let i = 0; i < res.data.data.records.length; i++) {
            let str1 = res.data.data.records[i].process.match(
              /[\u4e00-\u9fa5a-zA-Z]+/gi
            );
            let str2 = [];
            for (let j = 1; j <= str1.length; j++) {
              if (j % 2 === 1) {
                str2.push(str1[j]);
              }
            }
            this.missionList[i].process = str2;
          }
        } else {
          this.$message.warning(res.data.msg);
        }
      });
    },

    // 查询app列表
    async getAppAndMissionList() {
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      this.publicForm.sign = createSign(
        JSON.stringify({
          ...this.publicForm
        })
      );
      await API.getAppAndMissionList({
        ...this.publicForm
      }).then(res => {
        if (res.data.code === 0) {
          this.appAndMissionList = res.data.data.splice(1);
        } else {
          this.$message.warning(res.data.msg);
        }
      });
    },

    async getMissionList(appId) {
      let tForm = {};
      tForm.appId = appId;
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      this.publicForm.sign = createSign(
        JSON.stringify({
          ...tForm,
          ...this.publicForm
        })
      );
      await API.getMissionListFromApp({
        ...tForm,
        ...this.publicForm
      }).then(res => {
        if (res.data.code === 0) {
          this.existMissionList = res.data.data;
          console.log(this.existMissionList);
        } else {
          this.$message.warning(res.data.msg);
        }
      });
    },

    // 新增连续任务
    async addAutoMission() {
      if (this.form.taskName === '') {
        this.$message.warning('请先确认任务名称');
        return
      }
      this.dialogFormVisible = false;
      let Form = {
        organId: 0,
        list: []
      };
      Form.organId = JSON.parse(localStorage.getItem('updateUserInfo')).organId;
      Form.list = this.addForm;
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      this.publicForm.sign = createSign(
        JSON.stringify({
          ...Form,
          ...this.publicForm,
          ...this.form
        })
      );
      await API.getAutoMissionAdd({
        ...Form,
        ...this.publicForm,
        ...this.form
      }).then(res => {
        if (res.data.code === 0) {
          this.$message.success("新增成功");
        } else {
          this.$message.warning(res.data.msg);
        }
      });
      this.addForm = [
        {
          appName: "",
          taskName: ""
        },
        {
          appName: "",
          taskName: ""
        }
      ];
      this.optionFlag = true;
      this.getAutoMission();
    },

    // 修改任务流程时查询展示
    async getOneAutoMission() {
      let qForm = {};
      qForm.id = this.missionList[this.modifyIndex].id;
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      this.publicForm.sign = createSign(
        JSON.stringify({
          ...qForm,
          ...this.publicForm
        })
      );
      await API.getOneAutoMission({
        ...qForm,
        ...this.publicForm
      }).then(res => {
        if (res.data.code === 0) {
          this.modifyForm = res.data.data.list;
          for (let i = 0; i < this.appAndMissionList.length; i++) {
            if (this.appAndMissionList[i].name === this.modifyForm[0].appName) {
              this.modifyAppId = this.appAndMissionList[i].id;
              break;
            }
          }
        } else {
          this.$message.warning(res.data.msg);
        }
      });
    },

    // 修改连续任务
    async modifyButtonClick() {
      let mForm = {};
      mForm.id = this.missionList[this.modifyIndex].id;
      mForm.list = this.modifyForm;
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      this.publicForm.sign = createSign(
        JSON.stringify({
          ...mForm,
          ...this.publicForm
        })
      );
      await API.getAutoMissionUpd({
        ...mForm,
        ...this.publicForm
      }).then(res => {
        if (res.data.code === 0) {
          this.$message.success("修改成功");
        } else {
          this.$message.warning(res.data.msg);
        }
      });
      this.modifyMissionDialog = false;
      this.getAutoMission();
    },

    // 禁用/启用连续任务
    async changeAutoMissionState(item) {
      let mForm = {};
      mForm.id = item.id;
      mForm.enabled = Boolean(!(item.enabled * 1));
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      this.publicForm.sign = createSign(
        JSON.stringify({
          ...mForm,
          ...this.publicForm
        })
      );
      await API.getAutoMissionBan({
        ...mForm,
        ...this.publicForm
      }).then(res => {
        if (res.data.code === 0) {
          if (item.enabled === "1") {
            this.$message.success("禁用成功");
          } else {
            this.$message.success("启用成功");
          }
        } else {
          this.$message.warning(res.data.msg);
        }
      });
      this.getAutoMission();
    }
  },
  components: { ModuleTitle }
};
</script>

<style scoped>
/* 选项卡 */
.option-card {
  display: flex;
  width: 220px;
  height: 44px;
  border-radius: 3px;
  overflow: hidden;
  background-color: #f2f2f2;
  color: #333333;
  font-size: 18px;
}
.card-item {
  width: 50%;
  text-align: center;
  line-height: 44px;
}
.card-item-active {
  color: #ffffff;
  background-color: #1074fd;
  font-weight: bold;
  font-size: 18px;
}

/* 已有任务 列表 */
.list {
  height: 350px;
  width: 100%;
  margin-top: 40px;
}
.list-head {
  display: flex;
  width: 100%;
  height: 55px;
  background-color: #f2f2f2;
  border: 1px solid #d9d9d9;
}
.list-head-text {
  color: #1074fd;
  font-weight: bold;
  font-size: 16px;
  text-align: center;
  line-height: 53px;
}
.list-left-column {
  width: 18.8%;
  border-right: 1px solid #d9d9d9;
}
.list-middle-column {
  width: 62.2%;
  border-right: 1px solid #d9d9d9;
}
.list-right-column {
  width: 19%;
}
.list-body {
  display: flex;
  width: 100%;
  height: 50px;
  border: 1px solid #d9d9d9;
  border-top: none;
}
.list-body-content {
  text-align: center;
  line-height: 49px;
  color: #4d4d4d;
  font-size: 14px;
}
.work-flow {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.operation-button {
  display: flex;
  padding: 0 3%;
}
.modify-button {
  width: 50%;
  cursor: pointer;
  color: #1074fd;
}
.enabled-button {
  width: 50%;
  cursor: pointer;
  color: #00d655;
}
.disabled-button {
  width: 50%;
  cursor: pointer;
  color: #fd1e10;
}

/* 新增任务 表单 */
.add-form {
  height: 380px;
  width: 100%;
  margin-top: 30px;
  padding: 0 50px;
}
.add-form-button {
  margin-top: 40px;
  margin-bottom: 1.5px;
  text-align: right;
}
.submit-button {
  color: #fff;
  font-size: 18px;
  font-weight: 700;
  background-color: #1074fd;
}
.add-form-item {
  display: flex;
  height: 50px;
  width: 100%;
  line-height: 50px;
}
.order-number {
  display: inline-block;
  height: 24px;
  width: 24px;
  margin-right: 60px;
  border: 2px solid #1074fd;
  border-radius: 50%;
  line-height: 20px;
  text-align: center;
  font-style: normal;
  color: #1074fd;
}
.delete-button {
  display: inline-block;
  height: 28px;
  width: 28px;
  margin-top: 10px;
  margin-right: 10px;
  background-color: #ff5a5a;
  border-radius: 50%;
  line-height: 20px;
  text-align: center;
  color: #fff;
  font-style: normal;
  font-size: 50px;
  cursor: pointer;
}
.add-form-item-number {
  width: 10%;
}
.add-form-item-app {
  margin-top: 5px;
  width: 40%;
}
.add-form-item-mission {
  margin-top: 5px;
  width: 40%;
}
.add-form-item-delete {
  width: 10%;
  text-align: right;
}
.add-one-button {
  height: 44px;
  width: 100%;
  margin-top: 20px;
  background-color: #f2f2f2;
  border-radius: 5px;
  text-align: center;
  line-height: 44px;
  color: #999999;
  font-size: 16px;
}
.add-one-button:hover {
  background-color: #ccc;
}
/deep/ .add-form .el-scrollbar__thumb {
  background-color: transparent;
}
/deep/ #modDialog .el-scrollbar__thumb {
  background-color: #1074fd;
}
/deep/ .add-form .el-scrollbar__wrap,
/deep/ #modDialog .el-scrollbar__wrap {
  overflow-x: hidden;
}

/* 修改弹窗 */
.modify-dialog-button {
  width: 100%;
  margin-top: 25px;
  text-align: right;
}
.cancel-button {
  color: #4d4d4d;
  font-size: 14px;
}
.confirm-button {
  border-radius: 4px;
  background-color: #1074fd;
  color: #fff;
}

.noneList {
  position: relative;
  width: 100%;
  height: 356px;
  margin: 0 auto 40px;
  text-align: center;
  line-height: 356px;
  font-size: 30px;
}
</style>
